package com.ham.facade.impl;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Date;
import java.util.Iterator;
import java.util.List;

import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.DateUtil;
import org.apache.poi.ss.usermodel.Row;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.ham.common.AppUtil;
import com.ham.facade.ItemReaderFacade;
import com.ham.model.ItemModel;

public class ItemXLSReaderFacadeImpl extends MainFacadeImpl implements
		ItemReaderFacade {

	private static final Logger LOGGER = LoggerFactory
			.getLogger(ItemXLSReaderFacadeImpl.class);

	@Override
	public List<ItemModel> getItemList(String filePath) throws IOException {
		LOGGER.debug("Start processing " + filePath);
		FileInputStream fis = new FileInputStream(new File(filePath));
		HSSFWorkbook workbook = new HSSFWorkbook(fis);
		// Get first sheet from the workbook
		HSSFSheet sheet = workbook.getSheetAt(0);
		// Get iterator to all the rows in current sheet
		Iterator<Row> rowIterator = sheet.iterator();

		List<ItemModel> items = new ArrayList<ItemModel>();

		while (rowIterator.hasNext()) {// iterate up -> down each row
			ItemModel item = new ItemModel();
			Row row = rowIterator.next();
			Iterator<Cell> cellIterator = row.cellIterator();

			while (cellIterator.hasNext()) { // iterate from left -> right
				Cell cell = cellIterator.next();
				String cval = "";
				if (cell.getCellType() == Cell.CELL_TYPE_STRING) {
					cval = cell.getRichStringCellValue().toString();
				} else if (cell.getCellType() == Cell.CELL_TYPE_NUMERIC) {
					cval = String
							.valueOf(new Double(cell.getNumericCellValue())
									.intValue());
				}

				if (cell.getRowIndex() > 0) { // skip column title

					switch (cell.getColumnIndex()) {
					case 0:
						item.setId(cval);
						break;
					case 1:
						item.setName(cval);
						break;
					case 2:
						Date date = DateUtil.getJavaDate(Long.parseLong(cval));
						item.setPurchaseDate(AppUtil.formatDate(date));
						break;
					default:
						break;
					}
				}
			}

			if (row.getRowNum() > 0)
				items.add(item);

		}

		return items;

	}

}
